package com.myk.game.gobangchess.ai.startzone;

import java.util.Random;

public class GeneFixer {
    
    public static void main(String[] args) {

        int[] genes = {1, 1, 1, 1, 1, 0, 0, 1, 0, 0 ,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
        int m = 6; 
        int[][] baseBoard = {
            {3, 3, 3, 1, 2, 3, 3, 3, 3},
            {3, 3, 0, 0, 0, 0, 0, 0, 3},
            {3, -1, 0, 0, 0, 1, 0, 0, 3},
            {1, 0, 0, 1, 0, 0, 0, 0, 3},
            {2, 0, 0, 0, 2, 0, 0, 0, -1},
            {3, 0, 0, 0, 0, 0, 0, 0, 2},
            {3, -1, 0, 1, 0, 1, 0, 1, 3},
            {3, 0, 0, 0, 0, 1, 0, 3, 3},
            {3, 3, 3, 3, -1, 2, 3, 3, 3}
        };
        int color = 1; 
        
   
        int[] fixedGenes = fixGenes(genes, m, baseBoard, color);
        System.out.println("Fixed Genes:");
        for (int gene : fixedGenes) {
            System.out.print(gene + " ");
        }
    }

    public static int[] fixGenes(int[] genes, int m, int[][] baseBoard, int color) {
        int[] fixedGenes = new int[genes.length];
        int currentBestFitness = -1;
        
        for (int i = 0; i < 3; i++) {
            int[] tempGenes = genes.clone();
            int numOnes = sum(tempGenes);
            
            Random random = new Random();

            while(numOnes != m) {
                if (numOnes > m) {
                    int oneIndex;
                    do {
                        oneIndex = random.nextInt(tempGenes.length);
                    } while (tempGenes[oneIndex] != 1);
                    
                    tempGenes[oneIndex] = 0;
                } 
                if(numOnes < m) {
                    int zeroIndex;
                    do {
                        zeroIndex = random.nextInt(tempGenes.length);
                    } while (tempGenes[zeroIndex] != 0);
                    
                    tempGenes[zeroIndex] = 1;
                }
                numOnes = sum(tempGenes);
            };

            int fitnessThisTry = FitnessCalculator.getFitnessCodes(tempGenes, baseBoard, color); 
            if (fitnessThisTry >= currentBestFitness) {
                fixedGenes = tempGenes;
                currentBestFitness = fitnessThisTry;
            }
        }
        
        return fixedGenes;
    }
    
    private static int sum(int[] array) {
        int sum = 0;
        for (int i : array) {
            sum += i;
        }
        return sum;
    }


}
